import Axios from "axios";
import store from "@/store/store.js";
import Router from "../router";

export const getCode = (path, query) => {
  //let url=window.location.href
  console.log(query);
  let mpath = path;
  if (query && query.id != "") {
    mpath = path + "?id=" + query.id;
    console.log(mpath);
  }

  window.localStorage.setItem("turl", mpath);

  //let url2='http://localhost:8080/#/codelogin'
  //let url2 = "http://uiapi.qicubao.com/#/codelogin";
  //let url2 = "http://ui.lehuichengshi.com/codelogin";
  // let myurl =
  //   "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9b4743a1848616d3&response_type=code&scope=snsapi_userinfo&state=STATE&redirect_uri=" +
  //   url2 +
  //   "#wechat_redirect";
  // window.location.replace(myurl);
  let url2 = "http%3a%2f%2fui.lehuichengshi.com%2fcodelogin";
  let myurl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9b4743a1848616d3&redirect_uri=" + url2 + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
  window.location.replace(myurl);
};

export const codeLogin = code => {
  //Axios.post("/api/Mp/Login?code=" + code).then(res => {
    console.log(6666);
    console.log(code);
    console.log(6666);
	let postData = { code: code}
  Axios.post("/api/Mp/Login",postData ).then(res => {
	  console.log(res);
    if (res.data.data) {
      store.commit("changeUserinfo", res.data.data);
      let token = res.data.data.token.access_token;
      let access_token = "Bearer " + token;
      Axios.defaults.headers.common["Authorization"] = access_token;
      window.localStorage.setItem("token", token);
      window.localStorage.setItem("userinfo", JSON.stringify(res.data.data));
      window.localStorage.setItem("nickName", res.data.data.nickName);
      window.localStorage.setItem("avatarUrl", res.data.data.avatarUrl);
	  //renzheng();
	  if(res.data.data.isRegist == false){
		  Router.push({ path: "/register" });
	  }else{
      Router.push({ path: "/my" });
    }
	  
    }
  });
};
//https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx957fce2afd3a8a58&response_type=code&scope=snsapi_userinfo&state=STATE&redirect_uri=https://mp.yzgcw.com/&connect_redirect=1&uin=MjYwOTE1MzE0NA%3D%3D&key=017ad372b1a9e9bfd3392bd7759334edc39b7bf826e2a44dfb1c6afaabee937a35c9ff8d9f5ba9ddd598b0a3f65ace1a&pass_ticket=sDWsJhASevwHaaOEjwepNlvk8O0hroWM3OCdU+1L8XVpOdGKEsfxiC+UBzFvjaPqdBcUMP3VvBI78lrUAXsdng==
export const checkToken = () => {
  let token = window.localStorage.getItem("token");
  /**
	if(token==null || token==undefined || token=='undefined'){
        getCode()
	}else{}**/
  let access_token = "Bearer " + token;
  Axios.defaults.headers.common["Authorization"] = access_token;
  let nickName = window.localStorage.getItem("nickName");
  let avatarUrl = window.localStorage.getItem("avatarUrl");
  store.commit("changeUserinfo", { nickName: nickName, avatarUrl: avatarUrl });
  if (store.state.ispayRs.isOk == undefined) {
    renzheng();
  }
};

export const login = () => {
  let mtoken = window.localStorage.getItem("token");
  let url = window.location.href;

  console.log(mtoken);
  //return false
  if (mtoken == null) {
    if (url.indexOf("code") == -1) {
      let myurl =
        "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9b4743a1848616d3&response_type=code&scope=snsapi_userinfo&state=STATE&redirect_uri=" +
        url +
        "#wechat_redirect";
      window.location.replace(myurl);
    } else {
      let code = url.substring(url.indexOf("?code=") + 6, url.indexOf("&"));
      console.log(code, "我是code");
      Axios.get("/api/Mp/Login?code=" + code).then(res => {
        if (res.data.Data != null) {
          store.commit("changeUserinfo", res.data.Data);
          let token = res.data.Data.token.access_token;
          let access_token = "Bearer " + token;
          Axios.defaults.headers.common["Authorization"] = access_token;
          window.localStorage.setItem("token", token);
          window.localStorage.setItem("nickName", res.data.Data.nickName);
          window.localStorage.setItem("avatarUrl", res.data.Data.avatarUrl);
		  //renzheng();
		  //Router.push({ path: "/register" });
        }
      });
    }
  } else {
    let access_token = "Bearer " + mtoken;
    Axios.defaults.headers.common["Authorization"] = access_token;
    let nickName = window.localStorage.getItem("nickName");
    let avatarUrl = window.localStorage.getItem("avatarUrl");
    store.commit("changeUserinfo", {
      nickName: nickName,
      avatarUrl: avatarUrl
    });
    if (store.state.ispayRs.isOk == undefined) {
      renzheng();
    }
  }
};

export const mnlogin = () => {
  /**模拟登陆start**/

  //let url='/api/Trader/MiniLogin?openId=o8jC55Tki0tv-sP1p5S6jSBLpn3M'  //wht
  //let url='/api/Mp/MiniLogin?openId=o8jC55Y00l7-kU8sD7VbWpXClYuY' //zjl

  let url = "/api/Mp/MiniLogin?openId=oAc06xLfng0N9DLu7cuiEL_iVEmY"; //wht
  //let url='/api/Mp/MiniLogin?openId=oAc06xPuljw3FwtjNjnxkZ78kJFw' //zjl

  Axios.post(url).then(res => {
    if (res.data.Data != null) {
      let token = res.data.Data.access_token;
      //token =
        //"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJPcGVuSWQiOiJvOGpDNTVUa2kwdHYtc1AxcDVTNmpTQkxwbjNNIiwiVHJhZGVySWQiOiI1ODBkNDEzOS04M2Y0LTQ1NDQtYmJlMi1lMDUxMmQyZmMwZTEiLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL2V4cGlyYXRpb24iOiIyMDE5LzEwLzE4IDE6MjU6NTQgKzA4OjAwIiwibmJmIjoxNTcxMjczMTU0LCJleHAiOjE1NzEzMzMxNTQsImlzcyI6InpqbCIsImF1ZCI6ImV2ZXJ5b25lIn0.ULtA32r861IyJZtdQIrTr0PyUWKQsaVKUYBFnIRvamI";
      let access_token = "Bearer " + token;
      window.localStorage.setItem("token", token);
      Axios.defaults.headers.common["Authorization"] = access_token;

      renzheng();
      console.log(token);
    }
  });

  /**模拟登陆end**/
};

export const renzheng = () => {
  Axios.get("/api/WxPay/IsPayRenzheng").then(res => {
    let data = res.data.Data;
    if (data != null) {
      data.isOk = true;
    } else {
      data = { isOk: false };
    }

    store.commit("changeIspayRs", data);
    Axios.get("/api/WxPay/IsPayMinglu").then(res => {
      let data = res.data.Data;

      if (data != null) {
        data.isOk = true;
      } else {
        data = { isOk: false };
      }

      store.commit("changeIspayMl", data);
      let murl = window.localStorage.getItem("turl");
      Router.push({ path: murl });
    });
  });
};

export const formatDate = () => {
  var date = new Date();

  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();

  return [year, month, day].map(formatNumber).join("-");
};

const formatNumber = n => {
  n = n.toString();
  return n[1] ? n : "0" + n;
};
 
//Axios.defaults.headers.common[ 'Authorization']=access_token;
//Axios.defaults.headers.delete['Authorization'] = "Bearer " + localStorage.getItem('token');

export const RegistUrl = (params) => Axios.post('/api/Mp/Regist',params)
export const MemberPriceUrl = (params) => Axios.get('/api/Member/MemberPrice',params)
export const SmsValidCodeUrl = (params) => Axios.post('/api/Sms/ValidCode',params)
export const ConfigJs = (params) => Axios.get('/api/Mp/ConfigJs?url='+params);//配置JS SDK UnifiedOrder,OrderQuery,ConfigJs
export const OrderQuery = (params) => Axios.get('/api/Mp/OrderQuery?outNo='+params);//订单查询
export const RechargeOrderQuery = (params) => Axios.get('/api/Recharge/OrderQuery?outNo='+params);//订单查询
export const PayOrderOrderQuery = (params) => Axios.get('/api/PayOrder/OrderQuery?outNo='+params);//订单查询 
export const UnifiedOrder = (params) => Axios.post('/api/PayOrder/UnifiedOrder',params)
export const JifenUnifiedOrder = (params) => Axios.post('/api/Jifen/UnifiedOrder',params);//升级支付
export const JifenNotify = (params) => Axios.post('/api/Jifen/Notify',params)//异步通知
export const JifenOrderQuery = (params) => Axios.get('/api/Jifen/OrderQuery?outNo='+params);//订单查询 
export const MiniLogin = (params) => Axios.post('/api/Mp/MiniLogin',params)//异步通知